# -*- encodeing utf-8
import hashlib
import uuid

from flask import jsonify, request
from flask_login import login_required, login_user, current_user

from flask import Blueprint

from models import User ,OnLine

from dbconfig.extensions import db

user_bp = Blueprint('user_bp', __name__, url_prefix='/user')

@user_bp.route('/hello', methods=['GET'])
def hello():

    return jsonify({'code': 200, 'msg': "hello"})


@login_required
def record_login_history(type):
    online = OnLine()
    online.ID = str(uuid.uuid4())
    online.LOGINNAME = current_user.LOGINNAME
    online.IP = request.remote_addr
    online.TYPE = type
    db.session.add(online)

@user_bp.route('/login', methods=['POST'])
def do_login():
    #检查用户名是否存在
    user = User.query.filter_by(LOGINNAME=request.json['username']).first()
    print(user.to_json())
    if user is not None:
        md = hashlib.md5()
        md.update(request.json['password'].encode('utf-8'))
        if md.hexdigest() == user.PWD:
            login_user(user)
            record_login_history(1)
            return jsonify({'msg': '登录成功~', 'code': 200, 'url': '/', 'token': str(uuid.uuid4())})
    return jsonify({'msg': '登录失败,账号密码错误~', 'code': 500})
